package repository

import (
	"context"
	"server/internal/app/model"
	"server/internal/core/store"

	"gorm.io/gorm"
)

type SysRolePermissionRepository struct {
	db *gorm.DB
}

func NewSysRolePermissionRepository() *SysRolePermissionRepository {
	return &SysRolePermissionRepository{db: store.DB}
}

func (r *SysRolePermissionRepository) AssignPermission(ctx context.Context, roleID uint, permissionID ...uint) error {
	err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if err := tx.Delete(&model.SysRolePermission{}, "role_id = ?", roleID).Error; err != nil {
			return err
		}

		//批量插入
		rolePermissions := make([]model.SysRolePermission, len(permissionID))
		for i, permissionID := range permissionID {
			rolePermissions[i] = model.SysRolePermission{
				RoleID:       roleID,
				PermissionID: permissionID,
			}
		}
		if err := tx.CreateInBatches(&rolePermissions, 100).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}
